using dotnet_ef_admin.Src.Models;
using dotnet_ef_admin.Src.Services;
using dotnet_ef_admin.Src.Utilities;

using Microsoft.AspNetCore.Mvc;

namespace dotnet_ef_admin.Src.Controllers;

[Route("/api/v1/[controller]")] // 路由：api/v1/depts
[ApiController] // 标记控制器为Api控制器
public class DeptController(IDeptService _deptService) : ControllerBase {
    /// <summary>
    /// 获取所有部门。
    /// </summary>
    /// <returns>部门列表。</returns>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Dept>>> GetDepts([FromQuery] FindAllRequest request) {
        var depts = await _deptService.GetDeptsAsync(request);
        return Ok(depts);
    }

    /// <summary>
    /// 获取指定ID的部门。
    /// </summary>
    /// <param name="id">部门ID。</param>
    /// <returns>部门实例。</returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<Dept>> GetDept(int id) {
        var dept = await _deptService.GetDeptByIdAsync(id);
        if (dept == null) return NotFound();
        return Ok(dept);
    }

    /// <summary>
    /// 创建新部门。
    /// </summary>
    /// <param name="dept">部门实例。</param>
    /// <returns>创建的部门实例。</returns>
    [HttpPost]
    public async Task<ActionResult<Dept>> PostDept(Dept dept) {
        var newDept = await _deptService.CreateDeptAsync(dept);
        return Ok(newDept);
    }

    /// <summary>
    /// 更新指定ID的部门。
    /// </summary>
    /// <param name="id">部门ID。</param>
    /// <param name="dept">部门实例。</param>
    /// <returns>更新后的部门实例。</returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> PutDept(int id, Dept dept) {
        if (id != dept.Id) return BadRequest();

        var updatedDept = await _deptService.UpdateDeptAsync(dept);
        return Ok(updatedDept);
    }

    /// <summary>
    /// 删除指定ID的部门。
    /// </summary>
    /// <param name="id">部门ID。</param>
    /// <returns>删除操作结果。</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteDept(int id) {
        await _deptService.DeleteDeptAsync(id);
        return Ok("Deleted");
    }


    /// <summary>
    /// 获取部门选项列表。
    /// </summary>
    /// <returns>包含部门选项的列表。</returns>
    [HttpGet("options")]
    public async Task<ActionResult<List<TransformedItem>>> GetDeptOptions() {
        // 获取部门选项列表
        var deptOptions = await _deptService.GetDeptOptionsAsync();

        // 返回包含部门选项的列表
        return Ok(deptOptions);
    }
}
